package com.cloudcc.mobile.view.login;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.Manifest;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.Bind;
import butterknife.OnClick;

import com.alibaba.fastjson.JSON;
import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.EventList.ServerUrlEvent;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.LoginHistoryAdapter;
import com.cloudcc.mobile.adapter.LoginHistoryAdapter.OnHistoryItemClickListener;
import com.cloudcc.mobile.entity.LoginDBModel;
import com.cloudcc.mobile.entity.LoginSPModel;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.LoginPresenter;
import com.cloudcc.mobile.util.CheckApp;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UIUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.litesuits.android.log.Log;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;

import org.kymjs.kjframe.utils.PreferenceHelper;

/**
 * 登陆页
 *
 * @author Administrator
 */
public class LoginNewActivity extends BaseActivity implements
        OnHistoryItemClickListener {
    private String mEns = RunTimeManager.getInstance().getlanguage();
    @Bind(R.id.login_passswd)
    EditText tvPassword;
    @Bind(R.id.login_name)
    EditText tvUserName;
    @Bind(R.id.login_auto)
    CheckBox loginAuto;
    @Bind(R.id.login_remember_psw)
    CheckBox rememberMima;
    @Bind(R.id.login_btn)
    Button loginBtn;
    @Bind(R.id.login_user_img)
    ImageView loginuserimg;
    @Bind(R.id.login_key_img)
    ImageView loginkeyimg;
    @Bind(R.id.openDrop)
    ImageView openDrop;// 向下的点击

    private PopupWindow pWindow;

    private LoginPresenter loginPresenter = new LoginPresenter();

    //    private LoginDBModel mLoginModel;// 登录
    private LoginSPModel loginSPModel;
    private List<LoginSPModel> loginSPModels = new ArrayList<>();

    //权限
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_SMS,
            Manifest.permission.SEND_SMS,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.READ_CALL_LOG
    };

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        quanxian();
        addListener();
        fillUI();
        checkIsInstalled();
        initNewVersion();
    }

    private void checkIsInstalled() {
        if (CheckApp.checkAppInstalled(this, "com.cloudcc.mobile")) {
            Uri uri = Uri.fromParts("package", "com.cloudcc.mobile", null);
            Intent intent = new Intent(Intent.ACTION_DELETE, uri);
            startActivity(intent);
        }
    }

    private void initNewVersion(){
        new PgyUpdateManager.Builder()
                .setForced(false)                //设置是否强制更新,非自定义回调更新接口此方法有用
                .setUserCanRetry(false)         //失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
                .setDeleteHistroyApk(false)     // 检查更新前是否删除本地历史 Apk
                .setUpdateManagerListener(new UpdateManagerListener() {
                    @Override
                    public void onNoUpdateAvailable() {
                        //没有更新是回调此方法
                        if ("en".equals(mEns)) {
                            Toast.makeText(LoginNewActivity.this, "There is no latest version", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(LoginNewActivity.this, "没有最新版本", Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onUpdateAvailable(AppBean appBean) {
                        //更新是回调此方法
                        if ("en".equals(mEns)) {
                            showUpdateDialog(LoginNewActivity.this, "check for updates", "jump to download the latest version?");
                        } else {
                            showUpdateDialog(LoginNewActivity.this, "检查更新", "确认跳转去下载最新版本么？");
                        }
                    }


                    @Override
                    public void checkUpdateFailed(Exception e) {
                        //更新检测失败回调
                        if ("en".equals(mEns)) {
                            Toast.makeText(LoginNewActivity.this, "There is no latest version", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(LoginNewActivity.this, "没有最新版本", Toast.LENGTH_LONG).show();
                        }
                    }
                }).register();
    }

    public void showUpdateDialog(final Context context, String title,
                                 String message) {
        /**
         * 自定义的dialog
         */
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.setCancelable(false);
        View view = LayoutInflater.from(context)
                .inflate(R.layout.zhuxiao, null);
        builder.setView(view);
        builder.show();
        Button queren = (Button) view.findViewById(R.id.queren);
        Button quxiao = (Button) view.findViewById(R.id.quxiao);
        TextView titleName = (TextView) view.findViewById(R.id.titlename);
        TextView bodyName = (TextView) view.findViewById(R.id.bodyname);
        titleName.setText(title);
        bodyName.setText(message);
        queren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("https://www.pgyer.com/q3PD");
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(it);
            }
        });
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });
    }

//    private void fillUI() {
//
//        // #1 获得最后一个最近登录的帐号
//        mLoginModel = loginPresenter.getLastLogin();
//        // #1 判断是否是记住用户名
//
//        if (null != mLoginModel) {// 登录历史不为空 根据 记录判断
//            fillLogin();
//        } else {
//            clearEditText();
//        }
//        // 清空 缓存数据
//        RunTimeManager.getInstance().clearUserCache();
//        AsyncClient.getInstance().clear(mContext);
//    }

    private void fillUI() {
        String login = PreferenceHelper.readString(this, "loginInfo", "login", "");
        String logins = PreferenceHelper.readString(this, "loginInfo", "logins", "");

        if (login.length() > 0) {
            loginSPModel = JSON.parseObject(login, LoginSPModel.class);
        } else {
            loginSPModel = null;
        }
        if (login.length() > 0) {
            loginSPModels = JSON.parseArray(logins, LoginSPModel.class);
        }

        if (!"".equals(login)) {
            fillLogin();
        } else {
            clearEditText();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        finish();
        startActivity(intent);
    }

    /**
     * 根据 用户名以及 加密后的密码 转换
     *
     * @param userName
     * @param encryptPassword 加密后的密码
     */
//    private void fillLogin() {
//        if (mLoginModel == null) {
//            return;
//        }
//        rememberMima.setChecked(mLoginModel.isRememberUser);
//        loginAuto.setChecked(mLoginModel.isAutoLogin);
//        tvUserName.setText(mLoginModel.userName);
//
//        // 密码
//        String passwordForLogin = mLoginModel.getDecrypt();
//        tvPassword.setText(StringUtils.isBlank(passwordForLogin)
//                || (!mLoginModel.isRememberUser) ? StringUtils.EMPTY
//                : passwordForLogin);
//    }
    private void fillLogin() {
        if (loginSPModel == null) {
            return;
        }
        rememberMima.setChecked(loginSPModel.isRememberUser);
        loginAuto.setChecked(loginSPModel.isAutoLogin);
        tvUserName.setText(loginSPModel.userName);

        // 密码
        String passwordForLogin = loginSPModel.getDecrypt();
        tvPassword.setText(StringUtils.isBlank(passwordForLogin)
                || (!loginSPModel.isRememberUser) ? StringUtils.EMPTY
                : passwordForLogin);
    }

    private void addListener() {
        // 输入框输入监听
        tvUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                tvPassword.setText("");
                if (Tools.isNull(s.toString())) {
                    loginuserimg.setImageResource(R.drawable.login_user);
                } else {
                    loginuserimg
                            .setImageResource(R.drawable.login_user_hightlighted);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        tvPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (Tools.isNull(s.toString())) {
                    loginkeyimg.setImageResource(R.drawable.login_key);
                } else {
                    loginkeyimg
                            .setImageResource(R.drawable.login_key_hightlighted);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @OnClick(R.id.openDrop)
    public void clickedShowHistory() {
//        List<LoginDBModel> allLogins = loginPresenter.getAllLogins();
//        if (ListUtils.isEmpty(allLogins)) {
//            if("en".equals(mEns)){
//                Tools.showInfo(mContext, "No record!");
//            }else{
//                Tools.showInfo(mContext, mContext.getResources().getString(R.string.zwjl_tv));
//            }
//
//            return;
//        }
        String logins = PreferenceHelper.readString(this, "loginInfo", "logins", "");
        if(logins.length()>0) {
            showHistory(JSON.parseArray(logins, LoginSPModel.class));
        }
        else {
            if("en".equals(mEns)){
                Tools.showInfo(mContext, "No record!");
            }else{
                Tools.showInfo(mContext, mContext.getResources().getString(R.string.zwjl_tv));
            }
        }

    }

    private void showHistory(List<LoginSPModel> history) {
        dismissHistory();

        View contentView = LayoutInflater.from(mContext).inflate(
                R.layout.login_popp, null);
        ListView lvHistory = (ListView) contentView.findViewById(R.id.listview);

        LoginHistoryAdapter historyAdapter = new LoginHistoryAdapter(mContext);
        historyAdapter.addData(history);
        historyAdapter.setOnClickListener(this);

        lvHistory.setAdapter(historyAdapter);
        lvHistory.setDividerHeight(0);
        pWindow = new PopupWindow(contentView, tvUserName.getWidth(),
                LayoutParams.WRAP_CONTENT);
        pWindow.setFocusable(true);
        pWindow.setOutsideTouchable(true);
        pWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        pWindow.showAsDropDown(tvUserName);
    }

    private void dismissHistory() {
        if (pWindow != null) {
            pWindow.dismiss();
            pWindow = null;
        }
    }

    @OnClick(R.id.login_btn)
    public void btnLogin() {

        if ("en".equals(mEns)) {
            showWainting("logging...");
        } else {
            showWainting("正在登录...");
        }
        // loginPresenter.getAppUrl(tvUserName.getText().toString().trim());
        loginPresenter.login(tvUserName.getText().toString().trim(), tvPassword
                .getText().toString().trim());
    }

    /**
     * 获取应用登录 url
     *
     * @param event
     */
    public void onEventMainThread(ServerUrlEvent event) {
        if (event.isError()) {
            dismissWainting();
            Tools.showInfo(mContext, event.getMessage());
            return;
        }
        String url = event.getData().data.url;
        UrlTools.url = url + "/";
        UrlManager.APP_UR = url;
        UrlTools.weixinUrl = url;
        Log.d("loginurl", "loginurl" + url);
        loginPresenter.login(tvUserName.getText().toString().trim(), tvPassword
                .getText().toString().trim());
    }

    /**
     * 登录数据返回
     *
     * @param event
     */
    public void onEventMainThread(LoginEvent event) {
        dismissWainting();
        if (event.isError()) {
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Pro, username or password wrong, try again~~");
            } else {
                Tools.showInfo(mContext, "亲，用户名或密码错误，重试一下吧~~");
            }

            return;
        }
        // 当前 密码是 解密后的密码
        String encryptPassword = LoginDBModel.encryptPassword(tvPassword
                .getText().toString());
//        if (mLoginModel != null
//                && StringUtils.isNotBlank(mLoginModel.getPasswordEncrypt())) {// 将用户名密码保存到db中记录
//            loginPresenter.saveLoginToHistory(tvUserName.getText().toString()
//                            .trim(), encryptPassword, false, loginAuto.isChecked(),
//                    rememberMima.isChecked());
//        }

        android.util.Log.e("jx",tvPassword.getText().toString());
        LoginSPModel model = new LoginSPModel();
        model.setAutoLogin(loginAuto.isChecked());
        model.setPassword(encryptPassword);
        model.setRememberUser(rememberMima.isChecked());
        model.setUserName(tvUserName.getText().toString());
        boolean isNew = true;
        for (int i = 0; i < loginSPModels.size(); i++) {
            if (tvUserName.getText().toString().equals(loginSPModels.get(i).getUserName())) {
                isNew = false;
                loginSPModels.get(i).setUserName(tvUserName.getText().toString());
                loginSPModels.get(i).setRememberUser(rememberMima.isChecked());
                loginSPModels.get(i).setPassword(encryptPassword);
                loginSPModels.get(i).setAutoLogin(loginAuto.isChecked());
            }
        }
        if (isNew) {
            loginSPModels.add(model);
        }
        PreferenceHelper.write(this, "loginInfo", "logins", JSON.toJSONString(loginSPModels));
        PreferenceHelper.write(this, "loginInfo", "login", JSON.toJSONString(model));

        RunTimeManager.setAppBinding(event.getData().binding);
        RunTimeManager.setAppLanguage(event.getData().userInfo.lang);
        RunTimeManager.setId((event.getData().userInfo.orgId));
        RunTimeManager.setUserId((event.getData().userInfo.userId));

        RunTimeManager.setorgId((event.getData().userInfo.orgId));

        RunTimeManager.setJuese(event.getData().userInfo.roleName);
        RunTimeManager.setJiandang(event.getData().userInfo.profileName);
        RunTimeManager.setLoginname((event.getData().userInfo.loginName));
        RunTimeManager.setVersion(((event.getData().userInfo.version)));
        RunTimeManager.setTongshi(((event.getData().userInfo.showColleague)));
        RunTimeManager.setUserName((event.getData().userInfo.userName));
        RunTimeManager.setProfileId(event.getData().userInfo.profileId);
        UserModel user = event.getData().userInfo;
        if ("en".equals(event.getData().userInfo.lang)) {
            Resources resources = this.getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            Configuration config = resources.getConfiguration();
            // 应用用户选择语言
            config.locale = Locale.ENGLISH;
            resources.updateConfiguration(config, dm);

        } else {
            Resources resources = this.getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            Configuration config = resources.getConfiguration();
            // 应用用户选择语言
            config.locale = Locale.TRADITIONAL_CHINESE;
            resources.updateConfiguration(config, dm);
        }
        UserManager.getManager().saveUser(user);
//		if(isOPen(this)){
////			return;
//		}else{
//			openGPS(this);
//		}
        enterAPP();
        // Intent intent = new Intent(this, DingWeiService.class);

    }

    /**
     * 强制帮用户打开GPS
     *
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 进入app
     */
    private void enterAPP() {
        AppContext.isFenXiang = false;
        UIUtils.enterMainUI(mContext);
        finish();
    }

    @Override
    public void onSelectedLogin(LoginSPModel t, int position) {
        dismissHistory();
        loginSPModel = t;
        fillLogin();
    }

    @Override
    public void onClickDeleteLogin(LoginSPModel t, int position) {
        dismissHistory();
        if (tvUserName != null
                && TextUtils
                .equals(t.userName, tvUserName.getText().toString())) {
            clearEditText();
        }
//        loginPresenter.delLogin(t.userName);
        for (int i = 0; i < loginSPModels.size(); i++) {
            if (t.getUserName().equals(loginSPModels.get(i).getUserName())) {
                loginSPModels.remove(i);
                return;
            }
        }
        PreferenceHelper.write(this, "loginInfo", "logins", JSON.toJSONString(loginSPModels));
    }

    private void clearEditText() {
        tvPassword.setText("");
        tvUserName.setText("");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login2;
    }

    @Override
    protected boolean hasEventLife() {
        return true;
    }

    //权限
    private void quanxian() {

        List<String> needRequestPermissonList = findDeniedPermissions(needPermissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray(
                            new String[needRequestPermissonList.size()]),
                    2);
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     * checkSelfPermission方法是在用来判断是否app已经获取到某一个权限
     * shouldShowRequestPermissionRationale方法用来判断是否
     * 显示申请权限对话框，如果同意了或者不在询问则返回false
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED) {
                needRequestPermissonList.add(perm);
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(
                        this, perm)) {
                    needRequestPermissonList.add(perm);
                }
            }
        }
        return needRequestPermissonList;
    }
}
